from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ProcessPoolExecutor
from apscheduler.executors.pool import ThreadPoolExecutor
import subprocess
from pytz import utc


class Scheduler:
    def __init__(self, scheduler_type):
        self.scheduler = {
            "BlockingScheduler": BlockingScheduler,
            "BackgroundScheduler": BackgroundScheduler
        }
        self.jobstore = {
            'default': SQLAlchemyJobStore(url='mysql+pymysql://satellite_job:JhtSDWzp4TaidMP4@10.112.40.151:6506/satellite_job')
        }
        self.executor = {
            'threadpool': ThreadPoolExecutor(20),
            'processpool': ProcessPoolExecutor(5)
        }
        self.job_default = {
            'coalesce': False,
            'max_instances': 1
        }
        self.scheduler = self.scheduler[scheduler_type](jobstores=self.jobstore, executors=self.executor,
                                                        job_defaults=self.job_default, timezone=utc)
        self.add("1")
        self.scheduler.start()

    def call(self, path):
        print(path)
        subprocess.run(["python", path])

    def add(self, path):
        self.scheduler.add_job(self.call, trigger='interval', args=[path], id='1', name='a test job', jobstore='default',
                               executor='processpool', seconds=2)


scheduler = Scheduler("BlockingScheduler")
